package www.dashu.com.config;

import cn.hutool.core.util.StrUtil;
import www.dashu.com.constant.AuthConstant;
import com.nimbusds.jose.JWSObject;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

public class BaseFeginClientConfig
{
    @Bean
    public RequestInterceptor headerInterceptor()
    {

        return new RequestInterceptor()
        {
            @Override
            public void apply(RequestTemplate requestTemplate)
            {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

                String token = request.getHeader(AuthConstant.JWT_TOKEN_HEADER);
                String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
                if (!StrUtil.isEmpty(token)) {
                    try {
                        //从token中解析用户信息并设置到Header中去
                        JWSObject jwsObject = JWSObject.parse(realToken);
                        String userStr = jwsObject.getPayload().toString();
                        requestTemplate.header(AuthConstant.USER_TOKEN_HEADER, userStr);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

    }

}
